梦入琼楼寒有月,行过石树冻无烟

Laravel 视图

在Laravel框架中,为我们提供了一个blade.php的后缀扩展名,首先blade.php是由Laravel所提供的一个简单且强大的模板引擎,这与Spring boot所提供的Thyemeleaf类似。blade并不会限制在视图中使用的原生php code,所有blade视图文件都会被编译成原生的php code并将此缓存,除非被再次修改否则将不会被重新编译,并一般情况下存储在resources/views目录下。

路由与视图参数传递


所谓路由与参数进行传递,其实就是获取请求的信息并在blade.app内进行调用其函数并输出后的信息,即路由与视图参数:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

Route::get('/views/{name}', function ($name) {
return view('views', ['name' => $name]);
});

views.blade.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<h1>Hello,{{$name}}</h1>
</body>
</html>

视图共享


在Laravel之中,如果需要不同之间的视图进行数据的共享,我们可以使用app/Providers/目录下的AppServiceProvider.php类,在boot方法下写入需要共享的函数和参数即可:

AppServiceProvider.php

1
2
3
4
5
6
7
8
9
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->share('date','2021');
}

views.blade.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<h1>Hello,{{$date}}</h1>
</body>
</html>

判断视图是否存在


Laravel为我们提供了一种针对视图是否存在的方法exists,只需在路由web.php类中进行定义即可:

web.php

1
2
3
4
5
6
7
Route::get('/views', function () {
if (view()->exists('views')) {
echo "yes";
} else {
echo "no";
}
});

自定义错误页面


在Laravel项目之中,可以通过在resources/views/errors内新建各个HTTP状态码的对应blode.php页面,本文主要演示404页面:

404.blode.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>404</title>
</head>
<body>
<h1>404</h1>
</body>
</html>
⬅️ Go back